package com.qing.thread.communication;

/**
 * 线程通信：信号灯法
 */
public class SignalLight {
    public static void main(String[] args) {
        Tv tv = new Tv();

        new Player(tv).start();
        new Watcher(tv).start();

    }
}

//演员
class Player extends Thread {
    Tv tv;

    public Player(Tv tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 24; i++) {
            if (i % 2 == 0) {
                tv.ShowTime("西游记");
            } else if (i % 3 == 0) {
                tv.ShowTime("广告");
            } else {
                tv.ShowTime("王牌对王牌");
            }
        }
    }
}

//观众
class Watcher extends Thread {
    Tv tv;

    public Watcher(Tv tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 24; i++) {
            tv.WatchVoice();
        }
    }
}


//表演节目的载体（容器）
class Tv {
    //表演的节目
    String voice = "";

    //是否有节目产生 false没有节目，true有节目
    boolean flag = false;

    //电视表演节目
    public synchronized void ShowTime(String voice) {
        if (flag) {
            //如果有节目，就进入等待状态
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("Tv演出了：" + voice);
        this.voice = voice;
        //修改标识符
        this.flag = !this.flag;
        //通知观众观看
        this.notifyAll();

    }

    //观众观看节目
    public synchronized void WatchVoice() {
        //如果没有节目，则观众进入等待，电视开始生产节目
        if (flag == false) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        //观众消费节目
        System.out.println("观众观看了：" + voice);
        //观看节目后，修改标识符
        this.flag = !this.flag;
        //提示电视该播放节目了
        this.notifyAll();
    }
}